package com.atung.parking.service.impl;

import com.atung.parking.config.auth.AuthUserMangerContext;
import com.atung.parking.config.result.ApiResult;
import com.atung.parking.config.result.PageInfoResponse;
import com.atung.parking.config.tlPay.PayService;
import com.atung.parking.config.utils.OrderNumberGenerator;
import com.atung.parking.controller.DateConvertUtil;
import com.atung.parking.entity.BusParkingIot;
import com.atung.parking.entity.BusParkingIotPackage;
import com.atung.parking.entity.BusParkingOrders;
import com.atung.parking.entity.BusUser;
import com.atung.parking.enums.*;
import com.atung.parking.export.ParkingIotOrderExportVO;
import com.atung.parking.export.ParkingIotPackageOrderExportVO;
import com.atung.parking.export.PublicExportUtil;
import com.atung.parking.mapper.*;
import com.atung.parking.request.query.QueryOrdersRequest;
import com.atung.parking.request.save.SaveOrUpdateOrderRequest;
import com.atung.parking.request.save.SaveOrUpdatePackageOrderRequest;
import com.atung.parking.response.page.BillOrderResponse;
import com.atung.parking.response.page.OneselfOrderParkingResponse;
import com.atung.parking.response.page.OrderDetailsResponse;
import com.atung.parking.response.page.ParkingOrdersResponse;
import com.atung.parking.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.time.FastDateFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Administrator
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Resource
    private BusParkingOrdersMapper busParkingOrdersMapper;
    @Resource
    private BusParkingIotMapper busParkingIotMapper;

    @Resource
    private BusSuperUserMapper busSuperUserMapper;
    @Resource
    private BusParkingIotPackageMapper busParkingIotPackageMapper;
    @Resource
    private PublicExportUtil publicExportUtil;

    @Resource
    private BusUserMapper busUserMapper;
    @Resource
    private PayService payService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public BillOrderResponse saveParkingOrderService(SaveOrUpdateOrderRequest request) {
        BusUser busUser = busUserMapper.selectById(AuthUserMangerContext.getUserId());
        if (Objects.isNull(busUser)) {
            throw new RuntimeException("用户不存在");
        }
        //获取车场信息
        BusParkingIot busParkingIot = busParkingIotMapper.selectById(request.getParkingIotId());
        if (Objects.isNull(busParkingIot) ||
                !busParkingIot.getApprovalStatus().equals(ParkingIotApprovalState.APPROVED.getCode())) {
            throw new RuntimeException("车场信息不存在");
        }
        if (!StringUtils.hasText(busParkingIot.getSid())||!StringUtils.hasLength(busParkingIot.getSecretKey())) {
            throw new RuntimeException("当前车场暂无授权支付通道，请联系管理员配置授权信息");
        }
        LocalDateTime startDateTime = LocalDateTime.parse(request.getEstParkStartTime(), (java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
        // 将 LocalDateTime 转换为 Instant（使用 UTC 时区）
        Instant startInstant = startDateTime.toInstant(ZoneOffset.UTC);
//        Instant startInstant = Instant.ofEpochMilli(request.getEstParkStartTime());

        LocalDateTime endDateTime = LocalDateTime.parse(request.getEstParkEndTime(), (java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
        // 将 LocalDateTime 转换为 Instant（使用 UTC 时区）
        Instant endInstant = endDateTime.toInstant(ZoneOffset.UTC);
//        Instant endInstant = Instant.ofEpochMilli(request.getEstParkEndTime());
        if (System.currentTimeMillis() > endInstant.toEpochMilli()) {
            throw new RuntimeException("当前时间已经超过离开时间");
        }
        // 计算两个 Instant 对象之间的 Duration
        Duration duration = Duration.between(startInstant, endInstant);
        // 将 Duration 转换为小时数
        long hours = (duration.toMinutes() + 59) / 60;
        //获取单价
        BigDecimal ratePerHour = busParkingIot.getRatePerHour();
//        BigDecimal hoursBigDecimal = new BigDecimal(hours).setScale(0, RoundingMode.CEILING);
        BigDecimal orderAmount = ratePerHour
                .multiply(BigDecimal.valueOf(hours))
                .setScale(2, RoundingMode.HALF_UP);
        //获取订单金额

        if (orderAmount.compareTo(BigDecimal.ZERO) < 0) {
            throw new RuntimeException("金额出现异常");
        }
        BusParkingOrders busParkingOrders = new BusParkingOrders();
        //设置金额
        busParkingOrders.setOrderAmount(orderAmount);
        //设置车场
        busParkingOrders.setParkingIotId(request.getParkingIotId());
        //订单类型
        busParkingOrders.setOrderType(OrderType.PARKING_ORDER.name());
        //结束时间
        busParkingOrders.setEstParkEndTime(String.valueOf(startInstant.toEpochMilli()));
        //开始时间
        busParkingOrders.setEstParkStartTime(String.valueOf(endInstant.toEpochMilli()));
        //停车时长
        busParkingOrders.setEstParkDuration(Double.valueOf(hours));
        //订单编号
        busParkingOrders.setOrderNumber(OrderNumberGenerator.generateOrderNumber());
        //订单状态
        busParkingOrders.setOrderStatus(OrderState.PENDING_PAYMENT.getCode());
        //用户编号
        busParkingOrders.setUserId(AuthUserMangerContext.getUserId());
        //车牌号
        busParkingOrders.setLicensePlateNumber(request.getLicensePlate());
        //用户手机号
        busParkingOrders.setUserPhoneNumber(AuthUserMangerContext.getAuthUserEntity().getPhone());
        //客户编号
        busParkingOrders.setSuperUserId(busParkingIot.getSuperUserId());
        int insert = busParkingOrdersMapper.insert(busParkingOrders);
        if (insert != 1) {
            throw new RuntimeException("订单创建失败");
        }
        try {
            Object pay = payService.counterPay(busUser.getOpenId(), String.valueOf(busParkingOrders.getId()), busParkingOrders.getOrderAmount());
            BillOrderResponse billOrderResponse = new BillOrderResponse();
            BeanUtils.copyProperties(busParkingOrders, billOrderResponse);
            billOrderResponse.setParkingLotName(busParkingIot.getName());
            billOrderResponse.setEstParkEndTime(this.timestampToString(busParkingOrders.getEstParkEndTime()));
            //支付时间
            billOrderResponse.setEstParkStartTime(timestampToString(busParkingOrders.getEstParkStartTime()));
            billOrderResponse.setPayInfo(pay);
            return billOrderResponse;
        } catch (Exception E) {
            throw new RuntimeException(E.getMessage());
        }


    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public BillOrderResponse saveParkingPackageOrderService(SaveOrUpdatePackageOrderRequest request) {


        BusUser busUser = busUserMapper.selectById(AuthUserMangerContext.getUserId());
        if (Objects.isNull(busUser)) {
            throw new RuntimeException("用户不存在");
        }

        BusParkingIot busParkingIot = busParkingIotMapper.selectById(request.getParkingIotId());
        if (Objects.isNull(busParkingIot) ||
                !busParkingIot.getApprovalStatus().equals(ParkingIotApprovalState.APPROVED.getCode())) {
            throw new RuntimeException("车场信息不存在");
        }
        if (!StringUtils.hasText(busParkingIot.getSid())||!StringUtils.hasLength(busParkingIot.getSecretKey())) {
            throw new RuntimeException("当前车场暂无授权支付通道，请联系管理员配置授权信息");
        }
        BusParkingIotPackage busParkingIotPackage = busParkingIotPackageMapper.selectById(request.getParkingPackageId());
        if (Objects.isNull(busParkingIotPackage) ||
                !busParkingIotPackage.getState().equals(ParkingPackageState.ON_SHELF.getCode())
                || !busParkingIotPackage.getParkingIotId().equals(busParkingIot.getId())
        ) {
            throw new RuntimeException("套餐信息已下架或者暂无库存");
        }
        Integer stock = busParkingIotPackage.getStock() - 1;
        if (stock < 0) {
            throw new RuntimeException("暂无库存");
        }

        BusParkingOrders busParkingOrders = new BusParkingOrders();
        //设置金额
        busParkingOrders.setOrderAmount(busParkingIotPackage.getPackagePrice());
        //设置车场
        busParkingOrders.setParkingIotId(request.getParkingIotId());
        //订单类型
        busParkingOrders.setOrderType(OrderType.PACKAGE_ORDER.name());
        //套餐编号
        busParkingOrders.setParkingPackageId(busParkingIotPackage.getId());
        //使用时间
        busParkingOrders.setPackageUseDate(request.getPackageUseDate());
        //套餐类型
        busParkingOrders.setPackageType(busParkingIotPackage.getPackageType());
        //订单编号
        busParkingOrders.setOrderNumber(OrderNumberGenerator.generateOrderNumber());
        //订单状态
        busParkingOrders.setOrderStatus(OrderState.PENDING_PAYMENT.getCode());
        //用户编号
        busParkingOrders.setUserId(AuthUserMangerContext.getUserId());
        //车牌号
        busParkingOrders.setLicensePlateNumber(request.getLicensePlate());
        //用户手机号
        busParkingOrders.setUserPhoneNumber(AuthUserMangerContext.getAuthUserEntity().getPhone());
        //有效时段
        busParkingOrders.setPackageValidPeriod(busParkingIotPackage.getValidPeriodStart() + "-" + busParkingIotPackage.getValidPeriodEnd());

        //客户编号
        busParkingOrders.setSuperUserId(busParkingIot.getSuperUserId());
        int insert = busParkingOrdersMapper.insert(busParkingOrders);
        if (insert != 1) {
            throw new RuntimeException("订单创建失败");
        }

        Integer state = stock.equals(0) ? ParkingPackageState.SOLD_OUT.getCode() : ParkingPackageState.ON_SHELF.getCode();
        Integer updateStockById = busParkingIotPackageMapper.updateStockById(busParkingIotPackage.getId(), state, stock);
        if (updateStockById != 1) {
            throw new RuntimeException("订单创建失败");
        }


        try {
            Object pay = payService.counterPay(busUser.getOpenId(), String.valueOf(busParkingOrders.getId()), busParkingOrders.getOrderAmount());
            BillOrderResponse billOrderResponse = new BillOrderResponse();
            BeanUtils.copyProperties(busParkingOrders, billOrderResponse);
            billOrderResponse.setPackageValidPeriod(busParkingOrders.getPackageValidPeriod());
            billOrderResponse.setParkingLotName(busParkingIot.getName());
            billOrderResponse.setPayInfo(pay);
            return billOrderResponse;
        } catch (Exception E) {
            throw new RuntimeException(E.getMessage());
        }

    }

    @Override
    public PageInfoResponse<ParkingOrdersResponse> queryOrderParkingListService(QueryOrdersRequest request) {
        QueryWrapper<BusParkingOrders> queryWrapper = createQueryWrapper(request);
        Page<BusParkingOrders> page = new Page<>(request.getPageNum(), request.getPageSize());
        Page<BusParkingOrders> busParkingOrdersPage = busParkingOrdersMapper.selectPage(page, queryWrapper);
        List<ParkingOrdersResponse> collect = busParkingOrdersPage.getRecords().stream().map(item -> {
            ParkingOrdersResponse parkingOrdersResponse = new ParkingOrdersResponse();
            BeanUtils.copyProperties(item, parkingOrdersResponse);
            //获取停车场信息
            BusParkingIot busParkingIot = busParkingIotMapper.selectById(item.getParkingIotId());
            if (Objects.nonNull(busParkingIot)) {
                //设置停车场名称
                parkingOrdersResponse.setParkingIotName(busParkingIot.getName());
                //设置客户名称
                String superUserName = busSuperUserMapper.queryNameById(busParkingIot.getSuperUserId());
                parkingOrdersResponse.setSuperUserName(superUserName);
            }
            parkingOrdersResponse.setOrderStatus(OrderState.getDescriptionByCode(item.getOrderStatus()));
            //创建时间
            parkingOrdersResponse.setCreatorTime(this.timestampToString(item.getCreatorTime()));
            //支付时间
            parkingOrdersResponse.setOrderPaymentTime(timestampToString(item.getOrderPaymentTime()));
            //停車時間
            parkingOrdersResponse.setEstParkEndTime(this.timestampToString(item.getEstParkEndTime()));
            //取車時間
            parkingOrdersResponse.setEstParkStartTime(this.timestampToString(item.getEstParkStartTime()));
            return parkingOrdersResponse;
        }).collect(Collectors.toList());
        PageInfoResponse<ParkingOrdersResponse> pageResponse = new PageInfoResponse<>();
        pageResponse.setData(collect);
        pageResponse.setTotal(busParkingOrdersPage.getTotal());
        return pageResponse;
    }

    @Override
    public PageInfoResponse<ParkingOrdersResponse> queryOrderParkingPackageList(QueryOrdersRequest request) {

        QueryWrapper<BusParkingOrders> queryWrapper = createPackageQueryWrapper(request);
        Page<BusParkingOrders> page = new Page<>(request.getPageNum(), request.getPageSize());
        Page<BusParkingOrders> busParkingOrdersPage = busParkingOrdersMapper.selectPage(page, queryWrapper);

        List<ParkingOrdersResponse> collect = busParkingOrdersPage.getRecords().stream().map(item -> {
            ParkingOrdersResponse parkingOrdersResponse = new ParkingOrdersResponse();
            BeanUtils.copyProperties(item, parkingOrdersResponse);
            //获取停车场信息
            BusParkingIot busParkingIot = busParkingIotMapper.selectById(item.getParkingIotId());
            if (Objects.nonNull(busParkingIot)) {
                //设置停车场名称
                parkingOrdersResponse.setParkingIotName(busParkingIot.getName());
                //设置客户名称
                String superUserName = busSuperUserMapper.queryNameById(busParkingIot.getSuperUserId());
                parkingOrdersResponse.setSuperUserName(superUserName);
            }
            parkingOrdersResponse.setOrderStatus(OrderState.getDescriptionByCode(item.getOrderStatus()));
            parkingOrdersResponse.setPackageType(ParkingPackageType.getDescriptionByName(item.getPackageType()));
            //创建时间
            parkingOrdersResponse.setCreatorTime(this.timestampToString(item.getCreatorTime()));
            //支付时间
            parkingOrdersResponse.setOrderPaymentTime(this.timestampToString(item.getOrderPaymentTime()));

            return parkingOrdersResponse;
        }).collect(Collectors.toList());
        PageInfoResponse<ParkingOrdersResponse> pageResponse = new PageInfoResponse<>();
        pageResponse.setData(collect);
        pageResponse.setTotal(busParkingOrdersPage.getTotal());
        return pageResponse;
    }

    @Override
    public BigDecimal queryRevenueService(OrderType orderType) {
        QueryWrapper<BusParkingOrders> revenueQueryWrapper = createRevenueQueryWrapper(orderType);
        return busParkingOrdersMapper.selectList(revenueQueryWrapper).stream().map(BusParkingOrders::getOrderAmount).reduce(BigDecimal::add)
                .orElse(BigDecimal.ZERO);
    }

    @Override
    public void exportOrderParkingService(QueryOrdersRequest request, HttpServletResponse httpServletResponse) {
        QueryWrapper<BusParkingOrders> queryWrapper = createPackageQueryWrapper(request);
        List<BusParkingOrders> busParkingOrdersPage = busParkingOrdersMapper.selectList(queryWrapper);
        List<ParkingIotOrderExportVO> collect = busParkingOrdersPage.stream().map(item -> {
            ParkingIotOrderExportVO parkingIotOrderExportVO = new ParkingIotOrderExportVO();
            BeanUtils.copyProperties(item, parkingIotOrderExportVO);
            //获取停车场信息
            BusParkingIot busParkingIot = busParkingIotMapper.selectById(item.getParkingIotId());
            if (Objects.nonNull(busParkingIot)) {
                //设置停车场名称
                parkingIotOrderExportVO.setParkingIotName(busParkingIot.getName());
                //设置客户名称
                String superUserName = busSuperUserMapper.queryNameById(busParkingIot.getSuperUserId());
                parkingIotOrderExportVO.setSuperUserName(superUserName);
            }


            FastDateFormat formatter = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");
            // 格式化日期时间
            try {
                String formattedDate = formatter.format(Long.valueOf(item.getCreatorTime()));
                parkingIotOrderExportVO.setCreatorTime(formattedDate);
            } catch (Exception e) {
                parkingIotOrderExportVO.setCreatorTime("时间格式化出现问题");
            }
            //支付时间

            try {
                if (StringUtils.hasText(item.getOrderPaymentTime())) {
                    String formattedDate = formatter.format(Long.valueOf(item.getOrderPaymentTime()));
                    parkingIotOrderExportVO.setOrderPaymentTime(formattedDate);
                }

            } catch (Exception e) {
                parkingIotOrderExportVO.setOrderPaymentTime("时间格式化出现问题");
            }
            return parkingIotOrderExportVO;

        }).collect(Collectors.toList());
        try {
            publicExportUtil.exportReport(ExportType.PARKING_RESERVATION_ORDER_EXPORT, collect, httpServletResponse);
        } catch (Exception e) {

        }
    }

    @Override
    public void exportOrderParkingPackageService(QueryOrdersRequest request, HttpServletResponse httpServletResponse) {
        QueryWrapper<BusParkingOrders> queryWrapper = createPackageQueryWrapper(request);
        List<BusParkingOrders> busParkingOrdersPage = busParkingOrdersMapper.selectList(queryWrapper);
        List<ParkingIotPackageOrderExportVO> collect = busParkingOrdersPage.stream().map(item -> {
            ParkingIotPackageOrderExportVO parkingIotOrderExportVO = new ParkingIotPackageOrderExportVO();
            BeanUtils.copyProperties(item, parkingIotOrderExportVO);
            //获取停车场信息
            BusParkingIot busParkingIot = busParkingIotMapper.selectById(item.getParkingIotId());
            if (Objects.nonNull(busParkingIot)) {
                //设置停车场名称
                parkingIotOrderExportVO.setParkingIotName(busParkingIot.getName());
                //设置客户名称
                String superUserName = busSuperUserMapper.queryNameById(busParkingIot.getSuperUserId());
                parkingIotOrderExportVO.setSuperUserName(superUserName);
            }
            FastDateFormat formatter = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");
            // 格式化日期时间
            try {
                String formattedDate = formatter.format(Long.valueOf(item.getCreatorTime()));
                parkingIotOrderExportVO.setCreatorTime(formattedDate);
            } catch (Exception e) {
                parkingIotOrderExportVO.setCreatorTime("时间格式化出现问题");
            }
            //支付时间
            try {
                if (StringUtils.hasText(item.getOrderPaymentTime())) {
                    String formattedDate = formatter.format(Long.valueOf(item.getOrderPaymentTime()));
                    parkingIotOrderExportVO.setOrderPaymentTime(formattedDate);
                }

            } catch (Exception e) {
                parkingIotOrderExportVO.setOrderPaymentTime("时间格式化出现问题");
            }
            return parkingIotOrderExportVO;

        }).collect(Collectors.toList());
        try {
            publicExportUtil.exportReport(ExportType.PARKING_PACKAGE_ORDER_EXPORT, collect, httpServletResponse);
        } catch (Exception e) {

        }
    }

    @Override
    public List<OneselfOrderParkingResponse> oneselfOrderParkingListService(OrderState orderState) {

        QueryWrapper<BusParkingOrders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", AuthUserMangerContext.getUserId());
        if (Objects.nonNull(orderState)) {
            queryWrapper.eq("order_status", orderState.getCode());
        }
        queryWrapper.orderByDesc("creator_time");

        List<BusParkingOrders> busParkingOrders = busParkingOrdersMapper.selectList(queryWrapper);

        List<OneselfOrderParkingResponse> collect = busParkingOrders.stream().map(item -> {
            OneselfOrderParkingResponse parkingOrdersResponse = new OneselfOrderParkingResponse();
            BeanUtils.copyProperties(item, parkingOrdersResponse);
            //获取停车场信息
            BusParkingIot busParkingIot = busParkingIotMapper.selectById(item.getParkingIotId());
            if (Objects.nonNull(busParkingIot)) {
                //设置停车场名称
                parkingOrdersResponse.setParkingIotName(busParkingIot.getName());
            }
            parkingOrdersResponse.setOrderType(OrderType.getDescriptionByName(item.getOrderType()));
            if (OrderType.PARKING_ORDER.name().equals(item.getOrderType())) {
                //停車時間
                parkingOrdersResponse.setEstParkEndTime(this.timestampToString(item.getEstParkEndTime()));
                //取車時間
                parkingOrdersResponse.setEstParkStartTime(this.timestampToString(item.getEstParkStartTime()));
                //车位订单
            } else {
                parkingOrdersResponse.setPackageType(ParkingPackageType.getDescriptionByName(item.getPackageType()));
            }
            parkingOrdersResponse.setOrderStatus(OrderState.getDescriptionByCode(item.getOrderStatus()));
            //创建时间
            parkingOrdersResponse.setCreatorTime(this.timestampToString(item.getCreatorTime()));
            //支付时间
            parkingOrdersResponse.setOrderPaymentTime(timestampToString(item.getOrderPaymentTime()));

            return parkingOrdersResponse;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public ApiResult oneselfOrderDetailsService(Long id) {

        BusParkingOrders busParkingOrders = busParkingOrdersMapper.selectById(id);
        if (Objects.isNull(busParkingOrders) ||
                !busParkingOrders.getCreatorId().equals(String.valueOf(AuthUserMangerContext.getUserId()))) {
            return ApiResult.fail("数据不存在");
        }
        OrderDetailsResponse orderDetailsResponse = new OrderDetailsResponse();

        BeanUtils.copyProperties(busParkingOrders, orderDetailsResponse);
        orderDetailsResponse.setOrderStatus(OrderState.getDescriptionByCode(busParkingOrders.getOrderStatus()));
        BusParkingIot busParkingIot = busParkingIotMapper.selectById(busParkingOrders.getParkingIotId());
        if (Objects.nonNull(busParkingIot)) {
            //设置停车场名称
            orderDetailsResponse.setParkingIotName(busParkingIot.getName());
        }
        if (OrderType.PARKING_ORDER.name().equals(busParkingOrders.getOrderType())) {
            //停車時間
            orderDetailsResponse.setEstParkEndTime(this.timestampToString(busParkingOrders.getEstParkEndTime()));
            //取車時間
            orderDetailsResponse.setEstParkStartTime(this.timestampToString(busParkingOrders.getEstParkStartTime()));
            //车位订单
        }
        return ApiResult.ok(orderDetailsResponse);
    }

    public QueryWrapper<BusParkingOrders> createRevenueQueryWrapper(OrderType orderType) {
        QueryWrapper<BusParkingOrders> queryWrapper = new QueryWrapper<>();
        LocalDate today = LocalDate.now();
        // 生成今天的开始时间（00:00:00）
        LocalDateTime startOfToday = LocalDateTime.of(today, LocalTime.MIN);
        // 生成今天的结束时间（23:59:59.999）
        LocalDateTime endOfToday = LocalDateTime.of(today, LocalTime.MAX);
        // 转换为时间戳（毫秒）
        long startTimestamp = startOfToday.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        long endTimestamp = endOfToday.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        queryWrapper.between("creator_time", startTimestamp, endTimestamp);
        if (!AdminType.SUPERADMIN.equals(AuthUserMangerContext.getAuthUserEntity().getRoleType())) {
            queryWrapper.eq("super_user_id", AuthUserMangerContext.getUserId());
        }
        queryWrapper.eq("order_type", orderType.name());
        return queryWrapper;
    }

    public QueryWrapper<BusParkingOrders> createQueryWrapper(QueryOrdersRequest request) {
        QueryWrapper<BusParkingOrders> queryWrapper = new QueryWrapper<>();
        //车牌号
        if (StringUtils.hasText(request.getLicensePlateNumber())) {
            queryWrapper.like("license_plate_number", request.getLicensePlateNumber());
        }

        //订单编号
        if (StringUtils.hasText(request.getOrderNumber())) {
            queryWrapper.eq("order_number", request.getOrderNumber());
        }

        //车场编号
        if (StringUtils.hasText(request.getParkingIotId().toString())) {
            queryWrapper.eq("parking_lot_id", request.getParkingIotId());
        }
        //时间查询
        if (Objects.nonNull(request.getStartData()) && Objects.nonNull(request.getEndData())) {
            queryWrapper.between("creator_time", request.getStartData(), request.getEndData());
        }
        if (!AdminType.SUPERADMIN.equals(AuthUserMangerContext.getAuthUserEntity().getRoleType())) {
            queryWrapper.eq("super_user_id", AuthUserMangerContext.getUserId());
        }
        queryWrapper.eq("order_type", OrderType.PARKING_ORDER.name());
        queryWrapper.orderByDesc("creator_time");
        return queryWrapper;
    }

    public QueryWrapper<BusParkingOrders> createPackageQueryWrapper(QueryOrdersRequest request) {
        QueryWrapper<BusParkingOrders> queryWrapper = new QueryWrapper<>();

        //订单编号
        if (StringUtils.hasText(request.getOrderNumber())) {
            queryWrapper.eq("order_number", request.getOrderNumber());
        }
        //车牌号
        if (StringUtils.hasText(request.getLicensePlateNumber())) {
            queryWrapper.like("license_plate_number", request.getLicensePlateNumber());
        }
        //车场编号
        if (Objects.nonNull(request.getParkingIotId())) {
            queryWrapper.eq("parking_lot_id", request.getParkingIotId());
        }
        //判断是管理员还是客户
        if (AdminType.SUPERADMIN.equals(AuthUserMangerContext.getAuthUserEntity().getRoleType())) {
            if (Objects.nonNull(request.getSuperUserId())) {
                queryWrapper.eq("super_user_id", request.getSuperUserId());
            }
        } else {
            queryWrapper.eq("super_user_id", AuthUserMangerContext.getUserId());
        }

        //套餐类型
        if (Objects.nonNull(request.getPackageType())) {
            queryWrapper.eq("package_type", request.getPackageType().name());
        }
        //使用日期
        if (StringUtils.hasText(request.getPackageUseDate())) {
            queryWrapper.eq("package_use_date", request.getPackageUseDate());
        }
        //时间查询
        if (StringUtils.hasText(request.getStartData()) && StringUtils.hasText(request.getEndData())) {
            Long start = DateConvertUtil.convertQueryStartToMillis(request.getStartData());
            Long end = DateConvertUtil.convertQueryEndToMillis(request.getEndData());
            if (Objects.nonNull(request.getStartData()) && Objects.nonNull(request.getEndData())) {
                queryWrapper.between("creator_time", start, end);
            }

        }
        queryWrapper.eq("order_type", OrderType.PACKAGE_ORDER.name());
        queryWrapper.orderByDesc("creator_time");
        return queryWrapper;
    }

    public String timestampToString(String timestamp) {
        if (timestamp == null || timestamp.isEmpty()) {
            return null;
        }
        try {
            long timeInMillis = Long.parseLong(timestamp);
            Date date = new Date(timeInMillis);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.format(date);
        } catch (NumberFormatException e) {
            // 如果timestamp不是有效的长整型数字字符串，返回null或抛出异常
            return null;
        }
    }
}
